import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Button, Table, message, Input, Modal, Space } from 'antd'
import style from '../../filingCaseManage/CaseManage.module.less'
import nStyle from './Index.module.less'
import { awaitWrap, confirmAction, formatDate } from '@src/assets/js/tool'
import classNames from 'classnames'
import DetailInfo from '@components/DetailInfo'
const { Item } = Form
const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns (setData) {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 100
    },
    {
      title: '子机构数量',
      dataIndex: 'sub_institution_count',
      key: 'sub_institution_count',
      width: 100,
      align: 'center'
    },
    {
      title: '单位性质',
      dataIndex: 'nature',
      key: 'nature',
      width: 100
    },
    {
      title: '委员会成员数',
      dataIndex: 'board_num',
      key: 'board_num',
      width: 100,
      align: 'center'
    },
    {
      title: '工作人员数',
      dataIndex: 'staff_num',
      key: 'staff_num',
      width: 100,
      align: 'center'
    },
    {
      title: '仲裁秘书',
      dataIndex: 'employee_num',
      key: 'employee_num',
      width: 100,
      align: 'center',
      render: (v, line) => {
        if (v) {
          const c = v['仲裁秘书'] ? v['仲裁秘书'] : 0
          return <a onClick={() => { this.$openPage({ id: `InstitutionPersonList${line.id}`, title: `${line.name}人员列表`, componentName: 'InstitutionPersonList', meta: { id: line.tenant_code, formData: { type: '仲裁秘书' } } }) }}>{c}</a>
        }
      }
    },
    // {
    //   title: '案件审理人员',
    //   dataIndex: 'employee_num',
    //   key: 'employee_num',
    //   width: 100,
    //   render: (v, line) => {
    //     if (v) {
    //       const c = v['案件审理人员'] ? v['案件审理人员'] : 0
    //       return <a onClick={() => { this.$openPage({ id: `InstitutionPersonList${line.id}`, title: `${line.name}人员列表`, componentName: 'InstitutionPersonList', meta: { id: line.tenant_code, formData: { type: '案件审理人员' } } }) }}>{c}</a>
    //     }
    //   }
    // },
    {
      title: '仲裁管理人员',
      dataIndex: 'employee_num',
      key: 'employee_num',
      width: 100,
      align: 'center',
      render: (v, line) => {
        if (v) {
          const c = v['仲裁管理人员'] ? v['仲裁管理人员'] : 0
          return <a onClick={() => { this.$openPage({ id: `InstitutionPersonList${line.id}`, title: `${line.name}人员列表`, componentName: 'InstitutionPersonList', meta: { id: line.tenant_code, formData: { type: '仲裁管理人员' } } }) }}>{c}</a>
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (v) => {
        const disabled = v === '0'
        return <span className={classNames({ [nStyle.disabled]: disabled })}>{v === '1' ? '启用' : '注销'}</span>
      }
    },
    {
      title: '换届状态',
      dataIndex: 'elect_status',
      key: 'elect_status',
      width: 100
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 100,
      render: (v, l) => {
        return (
          <Space>
            <a onClick={() => setData(l)}>详情</a>
            {/* <a onClick={() => this.changeStatus(l)}>{l.status === '1' ? '注销机构' : '启用机构'}</a> */}
          </Space>
        )
      }
    }
  ]
}

class SecretaryStatistic extends Component {
  state = {
    dictionaries: {},
    causeActions: [],
    list: [],
    loading: false,
    orderField: '',
    order: '',
    currentData: null
  }

  formRef = React.createRef()

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 格式化表单数据
  formatParams (form) {
    form = form || this.formRef.current.getFieldsValue()
    const params = { }
    const condition = []
    if (form.name) {
      condition.push({ k: 'name', o: 'like', v: `%${form.name}%` })
    }
    params.condition = JSON.stringify(condition)
    return params
  }

  // 获取表格数据
  getTableData (form) {
    this.setState({ loading: true })
    this.$get('/api/mgt/institutionstat', this.formatParams(form))
      .then(res => {
        this.setState({ loading: false })
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          list: res.data.map((li, i) => {
            li.key = i + 1
            return li
          })
        })
      }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange (pagination, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order
    }, () => {
      this.getTableData()
    })
  }

  async changeStatusRequest (l) {
    const res = await this.$put(`/api/mgt/institutionstat/${l.id}`, {
      status: l.status === '1' ? '0' : '1'
    })
    return res.data
  }

  changeStatus (l) {
    confirmAction(`您确定要${l.status === '1' ? '注销' : '启用'}${l.name}吗？`, async () => {
      const h = message.loading('提交中', 0)
      const [e] = await awaitWrap(this.changeStatusRequest(l))
      h()
      if (e === null) {
        message.success('提交成功', 1)
        this.getTableData()
      }
    })
  }

  componentDidMount () {
    this.getTableData()
  }

  renderDetail () {
    let data = []
    const d = this.state.currentData
    if (d) {
      const names = (d.board_list && d.board_list instanceof Array ? d.board_list : []).map(li => li.name).join(',')
      data = [
        { k: '机构名称', v: d.name },
        { k: '机构简称', v: d.sname },
        { k: '机构英文名称', v: d.enname },
        { k: '机构英文简称', v: d.senname },
        { k: '统一社会信用代码', v: d.idno },
        { k: '执行机构（办公室）性质', v: d.nature },
        { k: '法定代表人', v: d.principal },
        { k: '住所', v: d.address },
        { k: '联系电话', v: d.tel },
        { k: '组成人员', v: names },
        { k: '简介', v: d.introduction },
        { k: '成立时间', v: d.founding_datetime ? formatDate(d.founding_datetime, 'YYYY-MM-DD') : '' },
        { k: '最近换届时间', v: d.elect_datetime ? formatDate(d.elect_datetime, 'YYYY-MM-DD') : '' },
        { k: '专业仲裁院数量', v: d.professional_court }
      ]
    }
    return (
      <Modal title='仲裁机构详情' width='1000px' open={this.state.currentData !== null} onCancel={() => this.setState({ currentData: null })} footer={false} forceRender>
        <DetailInfo data={data} />
      </Modal>
    )
  }

  render () {
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='名称' name='name'>
                    <Input placeholder='请输入' allowClear />
                  </Item>
                </Col>
                <Col span={8} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={getColumns.call(this, v => this.setState({ currentData: v }))} dataSource={this.state.list} pagination={false} onChange={(...args) => this.tableChange(...args)} />
        </div>
        {this.renderDetail()}
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(SecretaryStatistic)
